import { DefineComponent } from '../../../helpers/components'
import { MemberService } from '../../../logic_v2/services/member/member'
import { TemplateService } from '../../../logic_v2/services/ui/template_service'
import { UserService } from '../../../logic_v2/services/user'
import { AppError } from '../../../utils/error'
import { infoModal } from '../../../utils/modal'
import AutoRegister from '../../../behaviors/auto_register'
import { ReceiveCoupon } from '../../../typings/types/activity'
import { ActivityService } from '../../../logic_v2/services/activity/activity'
import { ActivityAdapter } from '../../../logic_v2/adapters/activity'
import { ActivityType, ReceiveActionType, ReceiveCouponButtonTheme } from '../../../helpers/constants/activity'
const userService = new UserService()
const templateService = new TemplateService()
const memberService = new MemberService()
const activityService = new ActivityService()
let timer: NodeJS.Timeout
DefineComponent({
  behaviors: [AutoRegister()],
  data: {
    sid: '',
    cardId: '',
    avatar: '',
    cardNo: '',
    qrcode: '',
    barcode: '',
    cardTypeName: '',
    refresh: 30,
    showReceived: false,
    receivedReward: {} as ReceiveCoupon,
    logo: '',
    receivedData: {} as ReceiveCoupon,
    showMemberRegister: false
  },
  computed: {

    maxHeight (data) {
      // 除了滚动区域的高度 100上边距+54上padding+22标题+24描述+16coupon上margin+88按钮区域
      let otherHeight = 56 + 56 + 22 + 24 + 16 + 88
      const receivedData = data.receivedData
      if (receivedData.received) {
        otherHeight += data.screenHeight * 0.3
      } else {
        otherHeight += 100
      }
      if (receivedData.reward && receivedData.reward.length > 0) {
        otherHeight += 44
      }
      if (receivedData.multiReward && receivedData.multiReward.length > 0) {
        otherHeight += 50
      }
      return `max-height: calc(100vh - ${otherHeight * 2}rpx);`
    },
    cover (data) {
      const receivedData = data.receivedData
      return [ActivityType.selfRegister, ActivityType.invitedRegister, ActivityType.advertisingRegister].includes(receivedData.type) ? '' : data.goodsCover
    }
  },
  methods: {
    onLoad (options: {cardId: string, sid: string}) {
      this.setData({
        cardId: options.cardId,
        sid: options.sid
      })
      this.getUserInfo()
      this.getQrcode()
      // this.setTimer()
    },
    onUnload () {
      clearInterval(timer)
    },
    clearTimer () {
      if (timer) {
        clearInterval(timer)
      }
    },
    setTimer () {
      this.clearTimer()
      timer = setInterval(() => {
        this.getQrcode()
      }, (this.data.refresh || 30) * 1000)
    },
    getUserInfo () {
      const avatar = userService.getAvatar()
      const config = templateService.getEmptyConfigByKey('avatar')
      const brandInfo = templateService.getGlobalBrandInfo()
      this.setData({
        avatar: avatar || config?.image || '',
        logo: brandInfo?.logo || ''
      })
    },
    async tapGetQrcode () {
      this.clearTimer()
      await this.getQrcode()
      this.setTimer()
    },
    async getQrcode () {
      const { cardId } = this.data
      if (cardId) {
        this.getCardQrcode()
      } else {
        this.getMemberQrcode()
      }
    },
    async getCardQrcode () {
      const { cardId } = this.data
      if (cardId) {
        // 会员卡的会员码
        try {
          const { cardNo, qrcode, barcode, cardTypeName, refresh } = await memberService.getCardQrCode(parseInt(cardId))
          this.setData({
            cardNo,
            cardTypeName,
            refresh,
            qrcode: 'data:image/png;base64,' + qrcode,
            barcode: 'data:image/png;base64,' + barcode
          })
        } catch (err) {
          if (err instanceof AppError) {
            infoModal({ title: '提示', content: err.msg })
          }
        }
      }
    },

    authPhoneNumber (e: WechatMiniprogram.CustomEvent) {
      const { isSuccess } = e.detail
      if (isSuccess) {
        this.setData({
          showMemberRegister: false
        })
        this.getMemberQrcode()
      }
    },

    async getMemberQrcode () {
      const { sid } = this.data
      try {
        const isVip = userService.isVIP()
        if (isVip) {
          const { code, qrcode, barcode, refresh } = await memberService.getMemberQrCode()
          this.setData({
            cardNo: code,
            refresh,
            qrcode: 'data:image/png;base64,' + qrcode,
            barcode: 'data:image/png;base64,' + barcode
          })
          console.debug('fea/sid', sid)
          if (parseInt(sid || '0') > 0) {
            // eslint-disable-next-line @typescript-eslint/ban-ts-comment
            // @ts-ignore
            this.autoRegShopProcess(true, sid)
          }
        } else {
          this.setData({
            showMemberRegister: true
          })
          const couponTemplate = await activityService.getCouponListByRegister({
            fromAd: 2,
            fromUid: 0
          })
          const receive = ActivityAdapter.genCouponAddContextByRegister(couponTemplate, {
            show: true,
            showType: 1,
            content: {
              firstRow: '',
              secondRow: '',
              button: ''
            },
            contextType: 1,
            textMode: 1,
            bgImg: '',
            url: '',
            width: 0,
            height: 0,
            existsVipGoods: true
          })
          receive.reward.title = '您暂无会员码, 请先注册'
          receive.reward.tips = `注册后, ${receive.reward.tips || '享受会员价'}`
          receive.reward.buttons = [
            { theme: ReceiveCouponButtonTheme.auth, text: '立即注册 领红包', action: ReceiveActionType.checkCoupon }
          ]
          this.setData({
            receivedData: receive.reward
          })
        }

      } catch (err) {
        if (err instanceof AppError) {
          infoModal({ title: '提示', content: err.msg })
        }
      }
    }
  }
})